#!/usr/bin/env python3
"""
Validate the new execute_sequential_commands tool
"""

import sys
import os
sys.path.insert(0, 'src')

def validate_function_added():
    """Validate that the function was properly added to server.py"""
    print("Validating new function implementation...")
    
    # Read server.py and check for the function
    with open('server.py', 'r') as f:
        content = f.read()
    
    # Check for key components
    checks = [
        ("Function decorator", "@mcp.tool\ndef execute_sequential_commands"),
        ("Function definition", "def execute_sequential_commands(connection_id: str, commands: str"),
        ("Working directory tracking", "current_working_dir = working_dir"),
        ("Command parsing", "command_lines = []"),
        ("CD command handling", "if command.startswith('cd ')"),
        ("Error handling", "stop_on_error: bool = True"),
        ("Import additions", "import os"),
        ("List type import", "from typing import Dict, Any, Optional, List")
    ]
    
    results = []
    for check_name, search_text in checks:
        if search_text in content:
            results.append(f"✅ {check_name}: Found")
        else:
            results.append(f"❌ {check_name}: Missing")
    
    for result in results:
        print(result)
    
    # Count total lines to verify substantial addition
    lines = content.split('\n')
    func_lines = [line for line in lines if 'execute_sequential_commands' in line]
    
    print(f"\nFunction implementation details:")
    print(f"  - Total lines in server.py: {len(lines)}")
    print(f"  - Lines containing 'execute_sequential_commands': {len(func_lines)}")
    print(f"  - File size: {len(content)} characters")
    
    return all("✅" in result for result in results)

def validate_readme_updated():
    """Check if README was updated with new tool info"""
    print("\nValidating README documentation...")
    
    try:
        with open('README.md', 'r') as f:
            readme_content = f.read()
        
        if 'execute_sequential_commands' in readme_content:
            print("✅ README updated with new tool")
            
            # Count mentions
            mentions = readme_content.count('execute_sequential_commands')
            print(f"  - Tool mentioned {mentions} times in README")
            
            # Check for key documentation
            doc_checks = [
                ("Tool description", "Execute multiple commands with session state"),
                ("Usage example", "cd /path/to/project"),
                ("make build", "make build"),
                ("sbatch", "sbatch")
            ]
            
            for check_name, search_text in doc_checks:
                if search_text in readme_content:
                    print(f"  ✅ {check_name} documented")
                else:
                    print(f"  ⚠️ {check_name} not found")
            
            return True
        else:
            print("❌ README not updated")
            return False
            
    except FileNotFoundError:
        print("❌ README.md not found")
        return False

def validate_example_files():
    """Check if example files were created"""
    print("\nValidating example files...")
    
    example_files = [
        'examples/your_specific_workflow.py',
        'examples/sequential_operations_example.py'
    ]
    
    results = []
    for file_path in example_files:
        if os.path.exists(file_path):
            results.append(f"✅ {file_path} exists")
            
            # Check file content
            with open(file_path, 'r') as f:
                content = f.read()
            
            if 'execute_sequential_commands' in content:
                results.append(f"  ✅ Contains sequential commands usage")
            else:
                results.append(f"  ⚠️ Missing sequential commands usage")
        else:
            results.append(f"⚠️ {file_path} not found")
    
    for result in results:
        print(result)

def test_workflow_syntax():
    """Test that the new tool syntax supports your specific workflow"""
    print("\nTesting workflow syntax support...")
    
    # Your specific workflow
    workflow_example = '''
    execute_sequential_commands(
        connection_id="user@server:22",
        commands="""
            cd /path/to/project1
            make build
            sbatch run.slurm
        """,
        working_dir="~",
        stop_on_error=True
    )
    '''
    
    print("Your workflow syntax:")
    print("=" * 40)
    print(workflow_example.strip())
    print("=" * 40)
    
    # Validate the syntax components
    syntax_checks = [
        ("Multi-line commands", '"""' in workflow_example),
        ("Working directory", "working_dir" in workflow_example),
        ("Error handling", "stop_on_error" in workflow_example),
        ("Your cd command", "cd /path/to/project1" in workflow_example),
        ("Your make command", "make build" in workflow_example),
        ("Your sbatch command", "sbatch run.slurm" in workflow_example)
    ]
    
    for check_name, passed in syntax_checks:
        status = "✅" if passed else "❌"
        print(f"{status} {check_name}")
    
    return all(passed for _, passed in syntax_checks)

def main():
    """Validate all aspects of the new sequential commands functionality"""
    print("SSH Slurm MCP Server - New Sequential Commands Tool Validation")
    print("=" * 70)
    
    tests = [
        ("Function Implementation", validate_function_added),
        ("README Documentation", validate_readme_updated), 
        ("Example Files", validate_example_files),
        ("Workflow Syntax", test_workflow_syntax)
    ]
    
    results = []
    for test_name, test_func in tests:
        print(f"\n{test_name}:")
        print("-" * len(test_name))
        try:
            result = test_func()
            results.append(result if result is not None else True)
        except Exception as e:
            print(f"❌ Test failed: {e}")
            results.append(False)
    
    passed = sum(results)
    total = len(results)
    
    print(f"\n" + "=" * 70)
    print(f"VALIDATION RESULTS: {passed}/{total} passed")
    
    if passed == total:
        print("🎉 NEW SEQUENTIAL COMMANDS TOOL SUCCESSFULLY IMPLEMENTED!")
        print("\n🚀 YOUR WORKFLOW IS NOW SUPPORTED:")
        print("   • cd /path/to/project1")
        print("   • make build") 
        print("   • sbatch run.slurm")
        print("   All in one tool call with persistent session state!")
        
        print("\n📋 NEW TOOL FEATURES:")
        print("   ✅ Multi-line command execution")
        print("   ✅ Working directory state tracking") 
        print("   ✅ Comment filtering (#)")
        print("   ✅ Error handling modes")
        print("   ✅ Detailed per-command output")
        print("   ✅ cd command intelligence")
        
        return 0
    else:
        print("⚠️ Some validation checks failed - see details above")
        return 1

if __name__ == "__main__":
    sys.exit(main())